﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Orchard.Users.Services;
using Orchard;
using Orchard.Security;
using Orchard.Core.Settings.Models;
using Orchard.Utility.Extensions;
using Orchard.Mvc;
using Orchard.Mvc.Extensions;
using Orchard.Localization;
using Orchard.ContentManagement;
using Orchard.Users.Models;
using Orchard.UI.Notify;
using Orchard.Logging;
using Orchard.Users.Events;
using Orchard.Themes;
using Contrib.Mod.ResetPassword.Services;

namespace Contrib.Mod.ResetPassword.Controllers
{
    [Themed]
    public class ResetController : Controller
    {
        private readonly IUserService _userService;
        private readonly IOrchardServices _orchardServices;
        private readonly IMembershipService _membershipService;
        private readonly IResetService resetService;
        private readonly IEnumerable<IUserEventHandler> _userEventHandlers;

        public ResetController(IUserService userService,
            IOrchardServices orchardServices,
            IMembershipService membershipService,
            IEnumerable<IUserEventHandler> userEventHandlers,
            IResetService resetService)
        {
            _userService = userService;
            _orchardServices = orchardServices;
            _membershipService = membershipService;
            _userEventHandlers = userEventHandlers;
            Logger = NullLogger.Instance;
            T = NullLocalizer.Instance;
            this.resetService = resetService;
        }

        public ILogger Logger { get; set; }
        public Localizer T { get; set; }

        int MinPasswordLength
        {
            get
            {
                return _membershipService.GetSettings().MinRequiredPasswordLength;
            }
        }

        [AlwaysAccessible]
        public ActionResult RequestPassword()
        {
            // ensure users can request lost password
            var registrationSettings = _orchardServices.WorkContext.CurrentSite.As<RegistrationSettingsPart>();
            if (!registrationSettings.EnableLostPassword)
            {
                return HttpNotFound();
            }

            var shape = _orchardServices.New.RequestPassword();

            return new ShapeResult(this, shape);
        }

        [HttpPost]
        [AlwaysAccessible]
        public ActionResult RequestPassword(string username)
        {
            // ensure users can request lost password
            var registrationSettings = _orchardServices.WorkContext.CurrentSite.As<RegistrationSettingsPart>();
            if (!registrationSettings.EnableLostPassword)
            {
                return HttpNotFound();
            }

            if (String.IsNullOrWhiteSpace(username))
            {
                _orchardServices.Notifier.Error(T("Invalid username or E-mail"));
                return RedirectToAction("RequestPassword");
            }

            var siteUrl = _orchardServices.WorkContext.CurrentSite.As<SiteSettings2Part>().BaseUrl;
            if (String.IsNullOrWhiteSpace(siteUrl))
            {
                siteUrl = HttpContext.Request.ToRootUrlString();
            }

            resetService.SendPasswordResetLink(username, nonce => Url.MakeAbsolute(Url.Action("LostPassword", "Account", new { Area = "Orchard.Users", nonce = nonce }), siteUrl));
            //resetService.SendPasswordResetLink(username, nonce => Url.MakeAbsolute(Url.Action("ForgottenPassword", "Reset", new { Area = "Contrib.Mod.ResetPassword", nonce = nonce }), siteUrl));

            _orchardServices.Notifier.Information(T("Check your e-mail for the confirmation link."));

            //return RedirectToAction("LogOn", "Account", new { Area = "Orchard.Users" });
            return RedirectToAction("LogOn", "Login", new { Area = "Contrib.Mod.RegistrationProviders" });
        }
        
        //public ActionResult ForgottenPassword(string nonce) {
        //    if ( _userService.ValidateLostPassword(nonce) == null ) {
        //        return RedirectToAction("LogOn", "Login", new { Area = "Contrib.Mod.RegistrationProviders" });
        //    }

        //    ViewData["PasswordLength"] = MinPasswordLength;

        //    var shape = _orchardServices.New.ForgottenPassword();

        //    return new ShapeResult(this, shape);
        //}

        //[HttpPost]
        //public ActionResult ForgottenPassword(string nonce, string newPassword, string confirmPassword)
        //{
        //    IUser user;
        //    if ( (user = _userService.ValidateLostPassword(nonce)) == null ) {
        //        return Redirect("~/");
        //    }

        //    ViewData["PasswordLength"] = MinPasswordLength;

        //    if (newPassword == null || newPassword.Length < MinPasswordLength) {
        //        ModelState.AddModelError("newPassword", T("You must specify a new password of {0} or more characters.", MinPasswordLength));
        //    }

        //    if (!String.Equals(newPassword, confirmPassword, StringComparison.Ordinal)) {
        //        ModelState.AddModelError("_FORM", T("The new password and confirmation password do not match."));
        //    }

        //    if (!ModelState.IsValid) {
        //        return RedirectToAction("ForgottenPassword", new { Nonce = nonce });
        //    }

        //    _membershipService.SetPassword(user, newPassword);

        //    foreach (var userEventHandler in _userEventHandlers) {
        //        userEventHandler.ChangedPassword(user);
        //    }

        //    return RedirectToAction("ChangePasswordSuccess", "Account", new { Area = "Orchard.Users" });
        //}
        
    }
}